package com.six.backend.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.six.backend.annotation.OperLog;
import com.six.backend.pojo.*;
import com.six.backend.service.ConferenceService;
import com.six.backend.service.ToolService;
import com.six.backend.shiro.Utils.Result;
import com.six.backend.utils.TokenUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 张重阳
 * @Date 2021-11-23 15:45
 * @Version 1.0
 */

@RestController
@Slf4j
@Transactional(rollbackFor=Exception.class)
@RequestMapping(value = "/tool", produces = "application/json;charset = utf-8")
public class ToolController {
    @Autowired
    private ToolService toolService;

    @Autowired
    private ConferenceService conferenceService;

    @PostMapping("createQuestionnaire")
    @ApiOperation("创建问卷")
    @OperLog(operModule = "工具模块",operType = "post",operDesc = "创建问卷操作")
    public Result createQuestionnaire(@RequestBody @Valid Questionnaire questionnaire, HttpServletRequest request) {
        String account = TokenUtil.getTokenName(request);
        questionnaire.setAccount(account);
        if (questionnaire.getCreateTime() == null) {
            questionnaire.setCreateTime(new Date());
        }
        Integer questionnaireId = toolService.postQuestionnaire(questionnaire);
        List<Question> topic = questionnaire.getTopic();
        boolean isInsertQuestion = toolService.postQuestion(topic,questionnaireId);
        if (questionnaireId > 0 && isInsertQuestion) {
            return new Result<>().setCode(200).setMessage("问卷创建成功");
        }
        return new Result<>().setCode(417).setMessage("问卷创建失败");
    }



    @GetMapping("/getTools")
    @ApiOperation("获取工具列表")
    @OperLog(operModule = "工具模块",operType = "get",operDesc = "获取工具列表操作")
    public Result getTools(@RequestParam(value = "userName",required = false) String userName,
                           @RequestParam(value = "conferenceName",required = false) String conferenceName,
                           @RequestParam(value = "agendaName",required = false) String agendaName,
                           @RequestParam(value = "pageSize",required = false) Integer pageSize,
                           @RequestParam(value = "pageNum",required = false) Integer pageNum,
                           HttpServletRequest servletRequest) {
        String account = TokenUtil.getTokenName(servletRequest);
        if (account == null) {
            return new Result<>().setCode(401).setMessage("请先登录");
        }
        Map map = new HashMap(3);
        map.put("userName",userName);
        map.put("conferenceName",conferenceName);
        map.put("agendaName",agendaName);
        map.put("account",account);
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum,pageSize);
            return new Result<>().setCode(200).setMessage("查询成功").setData(new PageInfo<>(toolService.getTools(map)));
        }
        return new Result<List<Tool>>().setCode(200).setMessage("查询成功").setData(toolService.getTools(map));
    }

    @GetMapping("/getAllTools")
    @ApiOperation("获取所有工具列表")
    @OperLog(operModule = "工具模块",operType = "get",operDesc = "获取所有工具列表操作")
    public Result getAllTools(@RequestParam(value = "userName",required = false) String userName,
                           @RequestParam(value = "conferenceName",required = false) String conferenceName,
                           @RequestParam(value = "agendaName",required = false) String agendaName,
                           @RequestParam(value = "pageSize",required = false) Integer pageSize,
                           @RequestParam(value = "pageNum",required = false) Integer pageNum) {
        Map map = new HashMap(3);
        map.put("userName",userName);
        map.put("conferenceName",conferenceName);
        map.put("agendaName",agendaName);
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum,pageSize);
            return new Result<>().setCode(200).setMessage("查询成功").setData(new PageInfo<>(toolService.getAllTools(map)));
        }
        return new Result<List<Tool>>().setCode(200).setMessage("查询成功").setData(toolService.getAllTools(map));
    }

    @GetMapping("/getToolDetails")
    @ApiOperation("查看详情")
    @OperLog(operModule = "工具模块",operType = "get",operDesc = "查看工具详情操作")
    public Result getToolDetails(@RequestParam("id") Integer toolId) {
        return new Result<>().setCode(200).setMessage("德尔菲列表查询成功").setData(toolService.getDelphi(toolId));
    }

    @GetMapping("getQuetionnaire")
    @ApiOperation("获取问卷")
    @OperLog(operModule = "工具模块",operType = "get",operDesc = "获取问卷操作")
    public Result getQuetionnaire(@RequestParam(required = false) String name,
                                  @RequestParam(required = false) Integer pageSize,
                                  @RequestParam(required = false) Integer pageNum) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum,pageSize);
        }
        return new Result<>().setCode(200).setMessage("查询成功").setData(new PageInfo<>(toolService.getQuestionnaire(name)));
   }

    @GetMapping("getQuestion")
    @ApiOperation("获取问卷题目")
    @OperLog(operModule = "工具模块",operType = "post",operDesc = "获取问卷题目操作")
    public Result getQuestion(@RequestParam Integer id) {
        return new Result<>().setCode(200).setMessage("查看成功").setData(toolService.getQuestion(id));
    }

    @DeleteMapping("deleteQuestionnaire")
    @ApiOperation("删除问卷")
    @OperLog(operModule = "工具模块",operType = "delete",operDesc = "删除问卷操作")
    public Result deleteQuestionnaire(@RequestParam Integer id) {
        List<Tool> toolList = toolService.getUsingToolsByQuestionnaireId(id);
        if (!toolList.isEmpty()) {
            return new Result<>().setCode(202).setMessage("该问卷已被使用，无法删除").setData(toolList);
        }
        if (toolService.deleteQuestionnaire(id)) {
            return new Result<>().setCode(200).setMessage("删除成功");
        }
        return new Result<>().setCode(417).setMessage("删除失败");
    }

    @PostMapping("putQuestionnaire")
    @ApiOperation("编辑问卷信息")
    @OperLog(operModule = "工具模块",operType = "put",operDesc = "编辑问卷信息操作")
    public Result editQuestionnaire(@RequestBody @Valid Questionnaire questionnaire,HttpServletRequest request) {

        //删除问卷
        Integer questionnaireId = questionnaire.getId();
        boolean b =  toolService.deleteQuestionnaire(questionnaireId);

        //添加问卷
        if (questionnaire.getCreateTime() == null) {
            questionnaire.setCreateTime(new Date());
        }
        String tokenName = TokenUtil.getTokenName(request);
        questionnaire.setAccount(tokenName);
        Integer newQuestionnaireId = toolService.postQuestionnaire(questionnaire);
        List<Question> topic = questionnaire.getTopic();
        boolean isInsertQuestion = toolService.postQuestion(topic,newQuestionnaireId);

        //返回值
        if (b && isInsertQuestion) {
            return new Result<>().setCode(200).setMessage("问卷修改成功");
        }
        return new Result<>().setCode(417).setMessage("问卷修改失败");
    }

    @GetMapping("/getToolUserName")
    @ApiOperation("获取人员列表")
    public Result getToolUserName(@RequestParam("id") Integer toolId) {
        return new Result<>().setCode(200).setMessage("获取人员列表成功").setData(toolService.getToolUserName(toolId));
    }

    @PutMapping("/endTool")
    @ApiOperation("结束工具")
    public Result endTool(@RequestBody Tool tool,HttpServletRequest servletRequest) {
        String account = TokenUtil.getTokenName(servletRequest);
        Integer conferenceId = tool.getConferenceId();
        if (conferenceId != null && !conferenceService.isConferenceHost(conferenceId,account)) {
            return new Result<>().setCode(202).setMessage("您不是主持人，无权结束工具");
        }
        if (toolService.endTool(tool.getId())) {
            return new Result<>().setCode(200).setMessage("工具已成功结束");
        }
        return new Result<>().setCode(202).setMessage("结束工具失败");
    }

    @PutMapping("/endDelphi")
    @ApiOperation("结束问卷")
    public Result endDelphi(@RequestBody Delphi delphi,HttpServletRequest servletRequest) {
        String account = TokenUtil.getTokenName(servletRequest);
        if (!toolService.isToolPusher(delphi.getToolId(),account)) {
            return new Result<>().setCode(202).setMessage("这不是您创建的工具，无权结束问卷");
        }
        Integer nextDelphiId = toolService.endDelphi(delphi.getId(), delphi.getToolId(), delphi.getTurn());
        return new Result<>().setCode(200).setMessage("问卷已成功结束").setData(nextDelphiId);
    }


    @PostMapping("/answerQuestionnaire")
    @ApiOperation("回答问卷")
    public Result answerQuestionnaire(@RequestBody UserAnswer userAnswer,
                                      HttpServletRequest servletRequest) {
        String name = TokenUtil.getTokenName(servletRequest);
        if (name != null) {
            userAnswer.setAccount(name);
            if (toolService.addUserAnswer(userAnswer)) {
                return new Result<>().setCode(201).setMessage("回答已提交");
            }
            return new Result<>().setCode(202).setMessage("用户未被推送该问卷");
        }
        return new Result<>().setCode(401).setMessage("用户未登录");
    }

    @GetMapping("/getUserFinishState")
    @ApiOperation("获取用户问卷完成状态")
    public Result getUserFinishState(@RequestParam("id") Integer delphi,
                                     @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                     @RequestParam(value = "pageNum",required = false) Integer pageNum) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum,pageSize);
            return new Result<>().setCode(200).setMessage("用户德尔菲问卷完成状态查询成功").setData(new PageInfo<>(toolService.getFinishState(delphi)));
        }
        return new Result<>().setCode(200).setMessage("用户德尔菲问卷完成状态查询成功").setData(toolService.getFinishState(delphi));
    }

    @GetMapping("/analyseUserAnswer")
    @ApiOperation("统计分析/历史结果")
    public Result analyseUserAnswer(@RequestParam("id") Integer delphi) {
        return new Result<>().setCode(200).setMessage("用户回答结果统计完成").setData(toolService.analyseUserAnswer(delphi));
    }

    @PostMapping("postTool")
    @ApiOperation("使用工具")
    @OperLog(operModule = "工具模块",operType = "post",operDesc = "使用工具接口")
    public Result useTool(@RequestBody RequestTool requestTool, HttpServletRequest request) {
        if(requestTool.getDelphis() == null || requestTool.getUsers() == null) {
            return new Result<>().setMessage("请完善信息").setCode(417);
        }
        String tokenName = TokenUtil.getTokenName(request);
        Integer firstDelphiId = toolService.useTool(requestTool, tokenName);
        if (firstDelphiId != null) {
            return new Result<>().setCode(200).setMessage("创建工具成功!").setData(firstDelphiId);
        }
        return new Result<>().setCode(417).setMessage("创建工具失败!");
    }

    @PutMapping("/startTool")
    @ApiOperation("推送工具")
    @OperLog(operModule = "工具模块",operType = "put",operDesc = "推送工具接口")
    public Result startTool(@RequestBody Tool tool,HttpServletRequest servletRequest) {
        String account = TokenUtil.getTokenName(servletRequest);
        Integer conferenceId = tool.getConferenceId();
        if (conferenceId != null && !conferenceService.isConferenceHost(conferenceId, account)) {
            return new Result<>().setCode(202).setMessage("您不是该会议的主持人，无法推送");
        }
        Integer firstDelphiId = toolService.startTool(tool.getId());
        if (firstDelphiId != null) {
            return new Result<>().setCode(200).setMessage("开启工具成功").setData(firstDelphiId);
        }
        return new Result<>().setCode(202).setMessage("开启工具失败");
    }

    @PutMapping("/startAgenda")
    @ApiOperation("推送议题")
    @OperLog(operModule = "工具模块",operType = "post",operDesc = "推送议题接口")
    public Result startAgenda(@RequestBody Tool tool,HttpServletRequest servletRequest) {
        String account = TokenUtil.getTokenName(servletRequest);
        if (!conferenceService.isConferenceHost(tool.getConferenceId(),account)) {
            return new Result<>().setCode(202).setMessage("您不是主持人，没有权限开启议题");
        }
        Integer firstDelphiId = toolService.startAgenda(tool.getId());
        if (firstDelphiId != null) {
            return new Result<>().setCode(200).setMessage("议题开启成功").setData(firstDelphiId);
        }
        return new Result<>().setCode(202).setMessage("还有议题正在进行，无法开始");
    }

    @GetMapping("/getToolUserAccount")
    @ApiOperation("获取工具的参会人员account")
    public Result getToolUserAccount(@RequestParam("id") Integer id) {
        return new Result<>().setCode(200).setMessage("获取参会人员account成功").setData(toolService.selectToolUserAccount(id));
    }
}

